package com.university.evaluation.config;

import com.university.evaluation.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // [MODIFIED] 使用 final 关键字，推荐的最佳实践
    private final JwtUtils jwtUtils;
    private final UserDetailsService userDetailsService;

    // [MODIFIED] 使用构造函数注入，代替 @Autowired 字段注入
    public JwtAuthenticationFilter(JwtUtils jwtUtils, UserDetailsService userDetailsService) {
        this.jwtUtils = jwtUtils;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain)
            throws ServletException, IOException {

        // [IMPROVEMENT] 移除了对 /login, /register 的判断
        // 因为 SecurityConfig 中已经配置了 permitAll, 过滤器不应对这些路径进行特殊处理
        // 让安全配置统一管理路径权限是更清晰的做法

        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String username;

        // 如果没有 Authorization 头，或者不是以 "Bearer " 开头，直接放行
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        jwt = authHeader.substring(7);
        try {
            username = jwtUtils.extractUsername(jwt);
        } catch (Exception e) {
            // 如果token解析失败（如过期），直接放行，后续的认证会失败
            logger.warn("JWT Token parsing failed: " + e.getMessage());
            filterChain.doFilter(request, response);
            return;
        }


        // 如果解析出用户名，并且当前安全上下文中没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证token是否有效
            if (jwtUtils.validateToken(jwt, userDetails)) {
                // 创建一个认证凭证
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        null, // 密码我们不需要，所以是null
                        userDetails.getAuthorities()
                );
                // 设置请求的详细信息
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证信息设置到安全上下文中
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}